#!/usr/bin/env python2
#-*- coding: utf-8 -*-


from Ump import utils, defs

from Ump.common import log, config
from Ump.common.mail import Mail

from Ump.objs.db import models
from Ump.objs.manager_base import Manager
from Ump.objs.session_wrapper import _sw


LOG = log.get_logger('Ump.Alert.api')



class AlertApi(object):
    def __init__(self):
        pass

    def alert_create(self, alert_values, is_snmp=True, is_mail=True, filter_host_id=None):
        """
        :param alert_values: dict|for create alert
        """
        detail = alert_values['detail']
        returncode = alert_values.get('returncode', '-1')
        filter_by = dict(returncode=returncode, is_handled=False, already_send_mail=True)
        if filter_host_id:
            filter_by['host_id'] = filter_host_id

        alert = models.Alert.query.filter_by(**filter_by).order_by(models.Alert.id.desc()).first()

        is_pass_day = True
        if alert:
            is_pass_day = utils.time_greater_than(alert.created_at, days=1)

        if is_pass_day:
            new_alert = models.Alert(alert_values).save()

            detail = alert_values['detail']

            if is_snmp:
                utils.exception_pass(self.send_snmp, detail)

            if is_mail and is_pass_day:
                utils.exception_pass(self.send_mail, detail)
                new_alert.update({'already_send_mail': True})
            else:
                LOG.debug('not need send mail :is_mail=%s, is_pass_day:%s' % (is_mail, is_pass_day))

    def send_snmp(self, msg):
        snmp_hosts = config.snmp_host
        for snmp_host in snmp_hosts:
            snmptrap_cmd = 'snmptrap -v 2c -c public %s:162 "" LICH-MIB::trapEvent \
                            SNMPv2-MIB::sysLocation.0 s "%s"' % (snmp_host, msg)
            utils.exception_pass(utils._exec_pipe, snmptrap_cmd)

    def send_mail(self, content, attachments=[], to_addrs=[]):
        mail_sql = _sw.get_one(model=models.Mail, id_or_spec={})
        if not mail_sql :
            return

        subject = content

        mail = Mail(mail_sql.mail, mail_sql.get_password)
        mail.attachments = attachments
        mail.mail_server = mail_sql.server
        mail.mail_port = int(mail_sql.port)
        if mail_sql.protocol == 'SSL':
            mail.use_ssl = True

        info = self.get_customer_info()
        content = content + '\n\n\n' + info
        
        rec_list = _sw.get_one(model=models.SysconfigForUMP, id_or_spec={'name':'mail_receive.list'})
        #an email contail attachments is daily report, mail_receive not receive daily report
        if not mail.attachments:
            if rec_list:
                for mail_address in str(rec_list.value_setting).split(';'):
                    if mail_address.strip():
                        mail.to_addrs += [mail_address]

            LOG.debug('send mail %s' % (str(mail.to_addrs)))
            if mail.to_addrs:
                res = mail.sendmail(subject, content)

        # if customer's callhome is enabled, send alert mail to mailsupporter
        customer = models.Customer.query.first()
        if (customer and customer.callhome):
            mail.to_addrs = [defs.MAILSUPPORT_ADDRESS]
            cluster = models.Cluster.query.first()
            subject = subject + ' Cluster UUID:%s' % (cluster.uuid)
            res = mail.sendmail(subject, content)


    def get_customer_info(self):
        customer = _sw.get_one(model=models.Customer, id_or_spec={})
        info = '' 
        if not customer :
            return info

        columns = ['company', 'contact', 'telephone', 'address']
        values = [getattr(customer, x) for x in columns]
        values = [x for x in values if x] 
        info = "\n".join(values)

        return info
        

if __name__ == '__main__':
    api = AlertApi()
    # api.alert_create({})
    api.send_mail()
   
